<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  ~   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  --%>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
    <title>操作业务数据</title>
    <style>

        .nav-tabs [class*="icon-"] {
            margin-right: 10px;
            font-size: 14px;
        }
        .nav>li>a {
            position: relative;
            display: block;
            padding: 0px 0px 5px 0px;
        }
        /*
        .table-striped > tbody > tr:nth-of-type(odd) {
            background-color: #f8f8f8;
        }
        */
        .table-hover > tbody > tr:hover {
            background-color: #f5f5f5;
        }

        .bg-white{
            background-color: white;
        }
        .popover-content {
            padding: 9px 14px;
        }
        .bwizard-steps {
            pointer-events: none !important;
            cursor: default !important;
        }


    </style>


    <script>

        var id = '${busiDataRuleId}';
        var SPLIT_CODE = String.fromCharCode(18);

        $(function () {

            $.post("${ctx}/busi-config/getBusiDataRule", {busiDataRuleId: id}, function (data) {
                if (data.success){
                    var row = data.result;
                    var conditionSqlForm = $('#condition-sql-form');
                    conditionSqlForm.find('[id="busiDataRuleId"]').val(id);
                    conditionSqlForm.find('[id="configSql"]').val(row['sql']);

                    $.post("${ctx}/busi-config/getBusiDataInfo", {busiDataRuleId: id}, function (data) {
                        if (data.success){
                            var busiDataInfo = $('#busi-data-info');
                            var info = data.result;
                            for (var key in info){
                                busiDataInfo.find('[id="'+key+'"]').html(info[key]).css('word-wrap','break-word');
                            }
                        }
                    });

                    $.post("${ctx}/busi-config/getSaveFields", {busiDataRuleId: id}, function (data) {
                        if (data.success){
                            var fields = data.result.split(SPLIT_CODE);
                            var columns = [{title:'', radio:true}];//单选钮，设置clickToSelect=true，则点击行能选中行，否则点在radionbox上才能选中
                            //var columns = [{title:'', checkbox:true}];//也可以单选，需要设置singleSelect=true，clickToSelect跟上面一样
                            for (var i = 0; i < fields.length; i++){
                                columns.push({title:fields[i], field:fields[i], width:'100px'});
                            }
                            //$('#database-data-table').bootstrapTable({columns:columns});
                            //$('#database-data-table').bootstrapTable('resetView',{height: 200});
                            $('#database-data-table').bootstrapTable('refreshOptions',{
                                columns:columns,
                                url:"",
                                onClickRow: function(row, $element){
                                    $.post("${ctx}/busi-config/getRedisKeys", {
                                        busiDataRuleId: id,
                                        row:encodeURIComponent($.toJSON(row))
                                    }, function (data) {
                                        if (data.success){
                                            var result = data.result;
                                            $('#redis-data-table').bootstrapTable('load', result);
                                        }
                                    });
                                }
                            }).bootstrapTable('removeAll');
                        }
                    });

                }
            });


            $('#read-busi-data-btn').click(function(){
                $('#database-data-table').bootstrapTable('refresh', {url: "${ctx}/busi-config/getDatabasePageData"});
            });

            $('#write-busi-data-btn').click(function(){
                var sqlCondition = $('#sqlCondition').val();
                $.post("${ctx}/busi-config/writeDataToRedis", {
                    busiDataRuleId: id, sqlCondition:sqlCondition, operFlag:0
                }, function (data) {
                    if (data.success){
                        toastr.success("已成功把SQL条件数据更新写入Redis！", "", {timeOut:0});
                    }
                });
            });
            $('#remove-busi-data-btn').click(function(){
                var sqlCondition = $('#sqlCondition').val();
                $.post("${ctx}/busi-config/writeDataToRedis", {
                    busiDataRuleId: id, sqlCondition:sqlCondition, operFlag:1
                }, function (data) {
                    if (data.success){
                        toastr.success("已成功把SQL条件数据从Redis中删除！", "", {timeOut:0});
                    }
                });
            });

            $('#save-redis-data').click(function () {
                var key = $('input[id="redis-key"]').val();
                if (key == ''){
                    toastr.warning("请输入Redis Key的值！");
                    return;
                }
                var valueType = $('input[name="valueType"]:checked').val();
                var value = {dataType: valueType};
                var data;
                switch (valueType){
                    case 'string':
                        data = $('#value-string').val();
                        if (data == ''){
                            toastr.warning("请输入"+valueType+"类型的值！");
                            return;
                        }
                        break;
                    default:
                        data = $('#table-'+valueType).bootstrapTable('getData');
                        if (data.length == 0){
                            toastr.warning("请输入"+valueType+"类型的值！");
                            return;
                        }
                }
                value.data = data;
                var params = {key: key, value: encodeURIComponent($.toJSON(value)), busiDataRuleId:id};
                $.post("${ctx}/busi-config/setRedisValueByKey", params, function (data) {
                    if (data.success){
                        toastr.success("成功更新Redis值！");
                        $('#redis-data-detail').modal('hide');
                    }
                });
            });



            $('input[id*="valueType-"]').click(function(){
                if ($(this).prop('checked')){
                    showValueView($(this).val());
                }
            });
            initTable();


        });

        function queryDatabasePageDataParams(params){
            var conditionSqlForm = $('#condition-sql-form');
            params.busiDataRuleId = conditionSqlForm.find('[id="busiDataRuleId"]').val();
            params.sqlCondition = conditionSqlForm.find('[id="sqlCondition"]').val();
            return params;
        }

        function operRedisFormatter(value, row, index){
            var e = '<a href="#" onclick="showRedisValue(\''+ row.key + '\')">修改值</a> ';
            return e;
        }

        function showRedisValue(key){
            $('[id*="table-"]').bootstrapTable('removeAll');

            $('#redis-key').val(key);
            var params = {key:key, busiDataRuleId: id};
            $.post('${ctx}/busi-config/getRedisValueByKey', params, function (data) {
                if (data.success){
                    var dataType = data.result.dataType;
                    showValueView(dataType);

                    var value = data.result.data;
                    if (dataType == 'string'){
                        $('#value-string').val(value);
                    }else{
                        $('#table-'+dataType).bootstrapTable('load', value);
                    }

                    $('#redis-data-detail').modal('show');
                }
            });
        }

        function showValueView(valueType) {
            $('[id*="view-"]').hide();
            $('[id*="view-' + valueType + '"]').show();
            $('input[id="valueType-'+valueType+'"]').prop('checked', 'checked');
        }

        function initTable() {
            $.fn.bootstrapTable.locales['zh-CN'] = {
                formatShowingRows: function (pageFrom, pageTo, totalRows) {
                    return '显示 ' + pageFrom + ' / ' + pageTo + '，共 ' + totalRows + ' 条 ';
                },
                formatRecordsPerPage: function (pageNumber) {
                    return '每页显示 ' + pageNumber + '条';
                },
                formatNoMatches: function () {
                    return '当前没有数据';
                }
            };

            var options = {
                uniqueId: "id",
                classes: "table table-hover table-no-bordered bg-white",
                striped: false,
                singleSelect: false,
                showHeader: true,
                pagination: true,
                pageSize: 5,
                pageList: [5, 20],
                //checkbox: true,
                //height: 235,
                sortable: false,
                locale: "zh-US"
            };

            $('#table-list,#table-set').bootstrapTable($.extend(options, {
                columns: [{
                    field: 'state',
                    checkbox: true
                }, {
                    title: '',
                    field: 'value',
                    halign: 'left',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入值'},
                    cellStyle: function (value, row, index) {
                        return {css: {'word-wrap': 'break-word', 'word-break': 'break-all'}};
                    }
                }],
            }));

            $('#table-zset').bootstrapTable($.extend(options, {
                onEditableSave: function (field, row, oldValue, $element) {
                    if (field == 'score') {
                        var newValue = parseFloat(row[field]);
                        //if (isNaN(newValue)){
                        if (row[field] == '' || isNaN(row[field])) {
                            toastr.warning("输入的权重值不合法！");
                            newValue = oldValue;
                        }
                        newValue += "";
                        $element.data('value', newValue);
                        row[field] = newValue;
                        setTimeout(function () {
                            $element.text(newValue);
                        }, 200);
                    }
                },
                columns: [{
                    field: 'state',
                    checkbox: true
                }, {
                    title: '值',
                    width: '90%',
                    field: 'value',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入值'},
                    cellStyle: function (value, row, index) {
                        return {css: {'word-wrap': 'break-word', 'word-break': 'break-all'}};
                    }
                }, {
                    title: '权重',
                    width: '10%',
                    field: 'score',
                    halign: 'right',
                    align: 'right',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入权重值'},
                    cellStyle: function (value, row, index) {
                        return {css: {'word-wrap': 'break-word', 'word-break': 'break-all'}};
                    }
                }],
            }));

            $('#table-hash').bootstrapTable($.extend(options, {
                columns: [{
                    field: 'state',
                    checkbox: true
                }, {
                    title: '字段名',
                    width: '50%',
                    field: 'field',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入字段名'},
                    cellStyle: function (value, row, index) {
                        return {css: {'word-wrap': 'break-word', 'word-break': 'break-all'}};
                    }
                }, {
                    title: '字段值',
                    width: '50%',
                    field: 'value',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入字段值'},
                    cellStyle: function (value, row, index) {
                        return {css: {'word-wrap': 'break-word', 'word-break': 'break-all'}};
                    }
                }],
            }));

            var initActionClick = function (valueType) {
                var tableList = $('#table-' + valueType);
                $("#appendBtn-" + valueType).click(function () {
                    if (valueType == 'zset') {
                        tableList.bootstrapTable('append', {value: '', score: 0}).bootstrapTable('lastPage');
                    } else if (valueType == 'hash') {
                        tableList.bootstrapTable('append', {field: '', value: ''}).bootstrapTable('lastPage');
                    } else {
                        tableList.bootstrapTable('append', {value: ''}).bootstrapTable('lastPage');
                    }
                });
                $('#removeBtn-' + valueType).click(function () {
                    var selections = tableList.bootstrapTable('getSelections');
                    if (selections.length == 0) {
                        if (tableList.bootstrapTable('getData').length == 0) {
                            toastr.warning("当前没有数据可供删除！");
                        } else {
                            toastr.warning("请在需要删除的数据前面打钩！");
                        }
                        return;
                    }
                    var values = $.map(selections, function (row) {
                        return row.value;
                    });
                    tableList.bootstrapTable('remove', {
                        field: 'value',
                        values: values
                    });
                });
            }
            initActionClick('list');
            initActionClick('set');
            initActionClick('zset');
            initActionClick('hash');
        }


    </script>
</head>

<body>

<div class="page-title">
    <h3>读写业务数据</h3>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="widget-container fluid-height clearfix">
            <div class="heading">
                <i class="icon-info"></i>配置信息
            </div>
            <div class="widget-content padded clearfix">
                <div class="row form-horizontal" id="busi-data-info">
                    <div class="col-md-3">
                        <label class="col-md-4" style="text-align: right; padding-right: 0px">配置名称：</label>
                        <span class="col-md-8" id="configName"></span>
                    </div>
                    <div class="col-md-3">
                        <label class="col-md-4" style="text-align: right; padding-right: 0px">所属集群：</label>
                        <span class="col-md-8" id="clusterName"></span>
                    </div>
                    <div class="col-md-3">
                        <label class="col-md-4" style="text-align: right; padding-right: 0px">所属业务：</label>
                        <span class="col-md-8" id="busiTypeName"></span>
                    </div>
                    <div class="col-md-3">
                        <label class="col-md-4" style="text-align: right; padding-right: 0px">Key前缀：</label>
                        <span class="col-md-8" id="keyPrefix"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <div class="widget-container fluid-height clearfix">
            <div class="heading">
                <i class="icon-search"></i>读写条件
            </div>
            <div class="widget-content padded clearfix">
                <form class="row form-horizontal" id="condition-sql-form">
                    <input type="hidden" id="busiDataRuleId">
                    <label class="col-md-1 control-label">select * from (</label>
                    <div class="col-md-5">
                        <textarea class="form-control" rows="3" id="configSql" readonly></textarea>
                    </div>
                    <label class="col-md-1 control-label">) where</label>
                    <div class="col-md-5">
                        <textarea class="form-control" id="sqlCondition" rows="3"></textarea>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <div class="widget-container fluid-height clearfix">
            <div class="heading">
                <i class="icon-table"></i>数据库数据【点击行，查询redis数据】
            </div>
            <div class="widget-content padded clearfix">
                <table id="database-data-table" data-toggle="table"
                       data-classes="table table-hover table-no-bordered bg-white"
                       data-striped="false" data-click-to-select="true" data-pagination="true"
                       data-side-pagination="server"
                       data-sortable="false" data-locale="zh-US" data-query-params="queryDatabasePageDataParams">
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <div class="widget-container fluid-height clearfix">
            <div class="heading">
                <i class="icon-table"></i>Redis数据
            </div>
            <div class="widget-content padded clearfix">
                <table id="redis-data-table" data-toggle="table" data-unique-id="id"
                       data-classes="table table-hover table-no-bordered bg-white" data-striped="false"
                       data-singleSelect="false" data-showHeader="true" data-pagination="false" data-sortable="true"
                       data-locale="zh-US">
                    <thead>
                    <tr>
                        <th data-field="key" data-title="Key列表" data-halign="left" data-align="left"
                            data-valign="middle" data-width="60%"></th>
                        <%--<th data-field="memory" data-title="内存占用（字节）"--%>
                            <%--data-halign="right" data-align="right" data-valign="middle" data-width="30%"></th>--%>
                        <th data-field="id" data-title="操作" data-formatter="operRedisFormatter"
                            data-halign="center" data-align="center" data-valign="middle" data-width="10%"></th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" id="read-busi-data-btn">读取SQL条件数据库数据</button>
            <button type="button" class="btn btn-primary" id="write-busi-data-btn">把SQL条件数据更新到Redis</button>
            <button type="button" class="btn btn-primary" id="remove-busi-data-btn">把SQL条件数据从Redis中删除</button>
        </div>
    </div>

</div>

<div class="modal fade" id="redis-data-detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" style="width: 900px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">修改Redis值</h4>
            </div>
            <form class="form-horizontal" id="redis-data-form">
                <div class="modal-body" style="margin-right: 20px">
                    <div class="form-group">
                        <label for="redis-key" class="col-md-1 control-label">键</label>
                        <div class="col-md-11">
                            <input type="text" class="form-control required" id="redis-key" name="redis-key" readonly
                                   placeholder="请输入Redis Key">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-1 control-label">值</label>
                        <div class="col-md-11">
                            <label class="radio-inline">
                                <input id="valueType-string" name="valueType" type="radio" value="string" checked>
                                <span>string</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-list" name="valueType" type="radio" value="list">
                                <span>list</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-set" name="valueType" type="radio" value="set">
                                <span>set</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-zset" name="valueType" type="radio" value="zset">
                                <span>zset</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-hash" name="valueType" type="radio" value="hash">
                                <span>hash</span>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="value-string" class="col-md-1 control-label"></label>
                        <div class="col-md-11" id="view-string">
                            <textarea class="form-control" id="value-string" name="value" placeholder="" rows="10"></textarea>
                        </div>
                        <div class="col-md-11" id="view-list">
                            <div class="col-md-11">
                                <table id="table-list"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-list" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-list" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-set">
                            <div class="col-md-11">
                                <table id="table-set"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-set" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-set" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-zset">
                            <div class="col-md-11">
                                <table id="table-zset"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-zset" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-zset" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-hash">
                            <div class="col-md-11">
                                <table id="table-hash"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-hash" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-hash" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="save-redis-data">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>
